package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"mall/common/globalkey"
	"strconv"
	"time"

	"mall/service/backend/common/utils/pointy"
	"mall/service/blog/rpc/blogclient"
	"mall/service/mqueue/job/internal/svc"
	// "github.com/pkg/errors"

	"github.com/hibiken/asynq"
)

// PublishPostProcessor implements asynq.Handler interface.
type PublishPostProcessor struct {
	svcCtx *svc.ServiceContext
}

func NewPublishPostProcessor(svcCtx *svc.ServiceContext) *PublishPostProcessor {
	return &PublishPostProcessor{
		svcCtx: svcCtx,
	}
}

// deferred Schedule Publish post : if return err != nil, asynq will retry
func (l *PublishPostProcessor) ProcessTask(ctx context.Context, t *asynq.Task) error {
	now := time.Now()
	endTime := now.Format("2006-01-02 15:04:05")
	startTime := now.Add(time.Minute * -31).Format("2006-01-02 15:04:05") //一分钟容错
	res, err := l.svcCtx.BlogRpc.BackendGetPostList(ctx, &blogclient.TmpPostListReq{
		StartTime: pointy.GetPointer(startTime),
		EndTime:   pointy.GetPointer(endTime),
		Status:    pointy.GetPointer(uint32(globalkey.PostStatusFuture)),
		WithMeta:  pointy.GetPointer(uint32(1)),
	})
	if err != nil {
		logx.Infof("PublishPostProcessor BackendGetPostList time:%+v, err:%v", endTime, err)
		return err
	}
	if len(res.List) > 0 {
		for _, v := range res.List {
			var pendingStatus *uint32
			if len(v.Meta) > 0 {
				for _, m := range v.Meta {
					if m.Key != nil && m.Value != nil && *m.Key == "pendingStatus" {
						if i, err := strconv.ParseInt(*m.Value, 10, 32); err == nil {
							pendingStatus = pointy.GetPointer(uint32(i))
						}
					}
				}
			}
			if pendingStatus != nil && *pendingStatus > 0 {
				_, err = l.svcCtx.BlogRpc.UpdatePost(ctx, &blogclient.PostInfo{
					Id:     v.Id,
					Status: pendingStatus,
				})
				if err != nil {
					logx.Infof("PublishPostProcessor UpdatePost Id:%+v, err:%v", v.Id, err)
					return err
				}
			}
		}
	}
	return nil
}
